package org.shj.spark.streaming;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.Optional;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class UpdateStateByKeyWordCount {

	public static void main(String[] args) throws Exception {
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("UpdateStateByKeyWordCount");
		JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
		
		//这一句很重要。UpdateStateByKey 需要上一批次的数据，所以内存很可能不够用，
		//那就需要保存数据。
		jsc.checkpoint("checkpoint");
		
		JavaReceiverInputDStream<String> stream = jsc.socketTextStream("ubuntu1", 8888);
		JavaDStream<String> words = stream.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = -8212938540949318738L;

			@Override
			public Iterator<String> call(String line) throws Exception {
				return Arrays.asList(line.split("\\+s")).iterator();
			}
		});
		
		JavaPairDStream<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Tuple2<String, Integer> call(String word) throws Exception {
				return new Tuple2<String, Integer>(word, 1);
			}
		});
		
		JavaPairDStream<String, Integer> wordCount = pairs.updateStateByKey(new Function2<List<Integer>, Optional<Integer>, Optional<Integer>>() {
			private static final long serialVersionUID = 1L;

			/**
			 * 实际上，对于每个单词，每次batch计算的时候都会调用这个函数，第一个参数 values 相当于这个batch中
			 * 这个key对应的新的一组值 ，可能有多个。比如 有两个(xuruyun，1），那么这个values就是（1，1）
			 * 那么第二个参数就表示的是这个key之前状态
			 */
			@Override
			public Optional<Integer> call(List<Integer> values, Optional<Integer> state) throws Exception {
				// optional其实有两个子类，一个是Some，一个是None
				//就是key有可能之前从来都没有出现过，意味着之前从来没有更新过状态
				Integer newValue = 0;
				if(state.isPresent()){
					newValue = state.get();
				}
				for(Integer val : values){
					newValue += val;
				}
				return Optional.of(newValue);
			}
		});
		
		wordCount.print();
		jsc.start();
		jsc.awaitTermination();
		jsc.close();

	}

}
